//https://leetcode.cn/problems/length-of-longest-fibonacci-subsequence/description/

class Solution {
public:
    int lenLongestFibSubseq(vector<int>& arr) 
    {
        int n = arr.size(), ans = 2;
        unordered_map<int, int> hash;
        for(int i = 0; i < n; i++) hash[arr[i]] = i;
        vector<vector<int>> dp(n, vector<int>(n, 2));
        for(int i = 2; i < n; i++)
        {
            for(int j = 1; j < i; j++)
            {
                int a = arr[i] - arr[j];
                if(a < arr[j] && hash.count(a))
                {
                    dp[j][i] = dp[hash[a]][j] + 1;
                }
                ans = max(ans, dp[j][i]);
            }
            
        }
        return ans < 3 ? 0 : ans;

    }
};